import { useMemberStore } from "../store";
import { useCookie, useRequestHeaders, type UseFetchOptions } from "nuxt/app";
import { message } from "ant-design-vue";
interface DataResult<T> {
  code: number;
  msg: string;
  data: T;
  message?: string;
  img?: string;
  captcha?: string;
  key?: string;
  ret?: boolean;
}

interface RequestParams {
  url: string;
  method: "GET" | "POST" | "PUT" | "DELETE";
  data?: Object;
  headers?: Record<string, string>;
  baseURL?: string;
}

const primaryKeyWhiteList: string[] = ["OnePage/json", "/Course/index"];

export default async <T>(params: RequestParams) => {
  const memberStore = useMemberStore();

  // 配置 useFetch 选项
  const options: UseFetchOptions<DataResult<T>> = {
    method: params.method,
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    headers: {
      ...params.headers,
      Lang: useCookie("lang").value || "en",
    },
    // mode: 'no-cors'
    // onRequest({options}) {
    //   options.headers['Lang'] = useCookie('lang').value || 'en'
    //   // options.headers['Content-Type'] = 'application/json
    // }
  };

  // 无缓存请求白名单
  if (primaryKeyWhiteList.includes(params.url)) {
    options.cache = "no-cache";
    options.key = `${params.url}-${uuid()}`;
  }

  // 添加认证 token
  if (memberStore.profile) {
    options.headers = {
      ...options.headers,
      Authorization: `Bearer ${memberStore.profile.token}`,
    };
  }

  // POST 请求参数安全处理
  const blackStringList = ["<script>", "</script>", "script", "alert"];
  if (params.method === "POST" && params.data) {
    let flag = true;

    Object.keys(params.data).forEach((key) => {
      if (typeof params.data[key] === "string") {
        if (blackStringList.some((item) => params.data[key].includes(item))) {
          flag = false;
          if (window.$vueLang) {
            message.error(window.$vueLang(`fail_params`));
          }
          return;
        }
      }
    });
    if (!flag) return;
  }

  // 处理请求体
  if (params.data) {
    if (params.method === "GET") {
      options.params = params.data;
    } else {
      options.body = params.data;
      const list = []
      // if (params.url) {
      //   options.body.lang = useCookie("lang").value || "en";
      // }
    }
  }

  try {
    const { data, error, headers } = await useFetch<DataResult<T>>(
      params.url,
      options
    );
    if (error.value) {
      return Promise.reject(error.value);
    }

    const response = data.value;

    if (!response) {
      console.error("No response data for request:", {
        url: params.url,
        method: params.method,
        status: error.value?.statusCode,
        message: error.value?.message,
      });
      return Promise.reject(
        new Error(`No response data received for ${params.url}`)
      );
    }

    // 保持与原有逻辑一致的响应处理
    if (response.code === 0) {
      return { data: response };
    }

    if (response.code === 10501) {
      response.msg = "server error";
      return { data: response };
    }

    return response;
  } catch (err) {
    console.error(err);
    return Promise.reject(err);
  }
};
